﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BDSimpleStatus.Models;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace BDSimpleStatus.Controllers
{
    public class bdssapiController : Controller
    {
        //
        // GET: /bdssapi/
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public ActionResult Index()
        {
            return View("Response");
        }

        // Does the work to verify servers.  
        public ActionResult Run()
        {
            BdssRepository repo = new BdssRepository();
            // Query for checks
            List<ServerCheckModel> scml = repo.GetServersToCheck();
            
            if (scml.Count < 1)
            {
                ViewBag.Response = "0";
                return View("Response");
            }
            // Run found checks
            Parallel.ForEach(scml, sc =>
            //foreach (var sc in scml)
            {
                sc.Message = string.Empty;
                Uri uri = null;
                try
                {
                    uri = new Uri(sc.URL);
                }
                catch (UriFormatException ufe)
                {
                    sc.Message = "**BAD URL***";
                    logger.ErrorException("Bad URL", ufe);
                    //continue;
                    return;
                }

                Checks.CheckPingAndHttp(sc, uri);
                double MinDiff = (DateTime.Now - sc.NextCheckDate).TotalMinutes;
                int multiplier = Convert.ToInt32(Math.Ceiling((MinDiff / (double)sc.Frequency)));
                logger.Debug("Multiplier value for next run date = {0} (span:{1}; f:{2}: where:{3})", multiplier.ToString(), MinDiff.ToString(), sc.Frequency.ToString(), sc.URL);
                sc.LastCheckDate = DateTime.Now;
                sc.NextCheckDate = sc.NextCheckDate.AddMinutes((double)(sc.Frequency * multiplier));
            });
            // Save ServerCheckModelList back to database
            repo.UpdateServerCheckList(scml);
            // Return something, so obscure status
            ViewBag.Response = scml.Count.ToString();
            return View("Response");
        }

        public ActionResult svars()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<html><body><table border='1'");
            for (int i = 0; i<Request.ServerVariables.Count; i++)
            {
                sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", Request.ServerVariables.AllKeys[i], Request.ServerVariables[i]);
            }
            sb.Append("</table></body></html>");
            ViewBag.Response = sb.ToString();
            return View("Response");
        }
    }
}
